package com.icesoft.system.safe.filter;

import com.icesoft.system.safe.helper.RequestHelper;
import com.icesoft.system.types.SystemSettingTypeDictionary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
@WebFilter(urlPatterns = "/actuator/*", filterName = "ipPathFilter")
public class IpPathFilter implements Filter {

	private SystemSettingTypeDictionary systemSettingTypeDictionary;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String userIp = RequestHelper.getRemoteIP((HttpServletRequest) request);
		if (RequestHelper.isLocalhost(userIp) || (systemSettingTypeDictionary.getWhiteIP() != null && systemSettingTypeDictionary.getWhiteIP().contains(userIp))) {
			chain.doFilter(request, response);
		} else {
			assert systemSettingTypeDictionary.getWhiteIP() != null;
			if (systemSettingTypeDictionary.getWhiteIP().contains(userIp)) {
				chain.doFilter(request, response);
			} else {
				log.warn("not white ip , userIp={}", userIp);
				HttpServletResponse res = (HttpServletResponse) response;
				res.setStatus(403);
			}
		}
	}

}
